import axios from "axios";
import {
    Toast
} from "vant";
import store from "@/store";
import {
    judgeClient,
    generateUUID,
    generateRandomString
} from './fun'
import Cookies from "js-cookie";
import md5 from 'js-md5';

import router from "@/router/index.js";
import {
    encrypt,
    decrypt,
} from './crypto'
// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.headers['Content-Type'] = 'text/plain';
// import CryptoJS from "crypto-js"; // 签名
// 签名相关信息
// const signatureKey = "35e4264138ceaaeeb37480d60c41a6a4"; // 示例,具体由后端提供
// 生成签名
// export const generSign = (val) =>
//     CryptoJS.HmacSHA256(val, signatureKey).toString() ?? "";
// 创建axios实例

const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.VUE_APP_BASE_API,
    // 超时
    timeout: 10000
})

let requertList = ['upload']

// 请求拦截器
service.interceptors.request.use(async config => {
    let iv = generateRandomString(16);
    let key = ''

    if (config.method == 'post') {
        //判断当前的请求接口是否包含在不需要加密的白名单中
        if (!requertList.some((item) => config.url.indexOf(item) > -1)) {
            //加密数据
            if (!store.state.app_key) {
                if (judgeClient() == 'android') {
                    key = '1hI2x3poSG7gRKWz';
                    config.headers["SeeYou-Did"] = 1;
                } else if (judgeClient() == 'ios') {
                    key = 'TiYaGpozmXBDsnRH';
                    config.headers["SeeYou-Did"] = 2;
                } else if (judgeClient() == 'h5') {
                    key = 'ayCBoqSuQkzsKbgJ';
                    config.headers["SeeYou-Did"] = 3;
                }
                config.data = iv + encrypt(JSON.stringify(config.data), key, iv)
            } else {
                config.data = iv + encrypt(JSON.stringify(config.data), store.state.app_key, iv)
            }
        }
    }

    // console.log(config);
    //接口类型：app,h5
    config.headers["Form-type"] = 'h5';
    //客户端类型：ios,android
    config.headers["SeeYou-ClientType"] = judgeClient();
    //时间戳，服务端允许客户端请求最大时间误差为3分钟
    config.headers["SeeYou-Timestamp"] = new Date().getTime();
    //API协议版本，可选值：1.0.0
    config.headers["SeeYou-Version"] = process.env.VUE_APP_V;

    //

    if (config.url == "/api/device") {
        config.headers["SeeYou-Sign"] = md5(`SeeYou-ClientType=${config.headers["SeeYou-ClientType"]}&SeeYou-Did=${config.headers["SeeYou-Did"]}&SeeYou-Timestamp=${config.headers["SeeYou-Timestamp"]}&SeeYou-Version=${config.headers["SeeYou-Version"]}${key}`); // 目前只支持POST请求
        Cookies.set("token1",md5(`SeeYou-ClientType=${config.headers["SeeYou-ClientType"]}&SeeYou-Did=${config.headers["SeeYou-Did"]}&SeeYou-Timestamp=${config.headers["SeeYou-Timestamp"]}&SeeYou-Version=${config.headers["SeeYou-Version"]}${key}`))
    } else {
        if (!config.headers["X-SeeYou-Authorization"]) {
            let token = store.state.token
            if (token) {
                config.headers["X-SeeYou-Authorization"] = "Bearer " + token ? "Bearer " + token : '';
            }
        }

        // 判断localStorage中是否已经存储了唯一标识符，如果没有则生成一个

        //每次请求都判断当前的uuid和app_key是否存在
        if (!store.state.did || !store.state.app_key) {
            await generateUUID();
        }

        // if(config.url=="/register/verify"){
        //     if (uuid || store.state.app_key) {
        //         uuid = await generateUUID();
        //     }
        // }else{
        //     if (!uuid) {
        //         uuid = await generateUUID();
        //         Cookies.set('uuid', uuid);
        //     }
        // }
        config.headers["SeeYou-Did"] = store.state.did;

        config.headers["SeeYou-Sign"] = md5(`SeeYou-ClientType=${config.headers["SeeYou-ClientType"]}&SeeYou-Did=${config.headers["SeeYou-Did"]}&SeeYou-Timestamp=${config.headers["SeeYou-Timestamp"]}&SeeYou-Version=${config.headers["SeeYou-Version"]}${store.state.app_key}`); // 目前只支持POST请求
    }
    // // ...其他请求头配置
    // // 处理签名 如果需要配置签名
    // // const data = config.data;
    // if (!config.headers.sign) {
    //     config.headers["SeeYou-Sign"] = md5(`SeeYou-ClientType=${config.headers["SeeYou-ClientType"]}&SeeYou-Did=${config.headers["SeeYou-Did"]}&SeeYou-Timestamp=${config.headers["SeeYou-Timestamp"]}&SeeYou-Version=${config.headers["SeeYou-Version"]}`); // 目前只支持POST请求
    // }
    return config;
})


// 响应拦截器
service.interceptors.response.use((response) => {
    const res = response.data;
    if (res.status == 400) { //失败
        Toast(res.msg);
        return Promise.reject(new Error(res.msg || 'Error'))
    } else if (res.status == 110002) { //请重新登录        
        Toast(res.msg);
        store.commit('SET_TOKEN', '');
        //跳转到登录页面
        router.replace('/Login')
        return Promise.reject(new Error(res.msg || 'Error'))
    } else if (res.status == 120000) { //签名验证失败
        Toast(res.msg);
        store.commit('SET_TOKEN', '');
        store.commit('SET_DID', '');
        store.commit('SET_APP_KEY', '');
        generateUUID();
        //跳转到登录页面
        router.replace('/Login')
        return Promise.reject(new Error(res.msg || 'Error'))
    }
    // console.log(res.data.substring(0,17));
    //解密数据
    if (res.data) {
        if (!store.state.app_key) {
            let key = ''
            if (judgeClient() == 'android') {
                key = '1hI2x3poSG7gRKWz';
            } else if (judgeClient() == 'ios') {
                key = 'TiYaGpozmXBDsnRH';
            } else if (judgeClient() == 'h5') {
                key = 'ayCBoqSuQkzsKbgJ';
            }
            // console.log(res.data.slice(16));
            // console.log(res.data.substring(0,16));
            // console.log(res.data);

            res.data = decrypt(res.data.slice(16), key, res.data.substring(0, 16))
        } else {
            // console.log(res.data);
            res.data = decrypt(res.data.slice(16), store.state.app_key, res.data.substring(0, 16))
        }
    }

    return res;
},
    // error => {
    //     console.log('err' + error) // for debug
    //     Toast(error);
    //     return Promise.reject(error)
    // }
);

export default service;